<template>
  <div class="richtext">
    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <span>是否自适应宽度</span>
        <el-switch
          v-model="autoWidth"
          active-color="#f40"
          inactive-color="#ccc"
          style="margin: 0px 10px"
        />
        <span>文件名字</span>
        <el-input
          v-model="filename"
          placeholder="请输入内容"
          style="width: 200px; margin: 0px 10px"
        />
        <span>文件格式</span>
        <el-select
          v-model="bookType"
          placeholder="请选择"
          style="margin: 0px 10px"
        >
          <el-option
            v-for="item in options"
            :key="item.value"
            :label="item.value"
            :value="item.value"
          />
        </el-select>
        <el-button
          style="float: right; margin-left: 4px"
          size="mini"
          type="success"
          @click="handleDownload"
        >xlsx导出表格</el-button>
        <el-button
          v-print="printObj"
          style="float: right; margin-left: 4px"
          size="mini"
          type="success"
        >vue-print-nb打印表格</el-button>
        <el-button
          style="float: right"
          size="mini"
          type="success"
          @click="handleDownloadHref"
        >href导出表格</el-button>
      </div>
      <div
        id="printMe"
        class="table_box"
        style="background: #f8f8f8; width: 100%"
      >
        <!-- <el-table id="tablediv7" :data="tableData" border style="width:100%">
          <el-table-column align="center" label="姓名" prop="name" width="10%" />
          <el-table-column align="center" label="地址" prop="address" width="20%" />
          <el-table-column align="center" label="日期" prop="date" width="10%" />
          <el-table-column align="center" label="时间戳1" prop="timestamp1" width="10%" />
          <el-table-column align="center" label="时间戳2" prop="timestamp2" width="10%" />
          <el-table-column align="center" label="时间戳3" prop="timestamp3" width="10%" />
          <el-table-column align="center" label="时间戳4" prop="timestamp4" width="10%" />
          <el-table-column align="center" label="时间戳5" prop="timestamp5" width="20%" />
        </el-table> -->
        <table id="printMe" class="my_test_table">
          <thead>
            <th>姓名</th>
            <th class="t_address">地址</th>
            <th>日期</th>
            <th>时间戳1</th>
            <th>时间戳2</th>
            <th>时间戳3</th>
            <th>时间戳4</th>
            <th>时间戳5</th>
          </thead>
          <tbody>
            <tr v-for="(ir, irx) in tableData" :key="irx">
              <td v-for="(id, idx) in ir" :key="idx" :class="idx===1?'t_address':''">
                {{ id }}
              </td>
            </tr>
          </tbody>
        </table>
      </div>
    </el-card>

    <el-card class="box-card" style="margintop: 20px">
      <div slot="header" class="clearfix">
        <div>
          <input
            ref="excel-upload-input"
            class="excel-upload-input"
            type="file"
            accept=".xlsx, .xls "
            @change="handleClick"
          >
          <el-button
            size="mini"
            type="success"
            @click="btnClick"
          >上传表格</el-button>
        </div>
      </div>
      <div>
        <el-table :data="tableData2" border highlight-current-row>
          <el-table-column
            v-for="item of tableHeader"
            :key="item"
            :prop="item"
            :label="item"
          />
        </el-table>
      </div>
    </el-card>
  </div>
</template>

<script>
import { parseTime } from '@/utils' // 这里是文件下载 对时间戳格式数据做解析而已可以不要
import * as XLSX from 'xlsx' // 这里用于文件上传
import print from 'vue-print-nb'
export default {
  name: 'Excel',
  directives: {
    print
  },
  data() {
    return {
      // 文件导出
      filename: '',
      autoWidth: true,
      bookType: 'xlsx',
      options: [
        {
          value: 'xlsx'
        },
        {
          value: 'xls'
        },
        {
          value: 'csv'
        },
        {
          value: 'txt'
        }
      ],
      tableData: [],

      // 文件导入
      tableData2: [],
      tableHeader: [],
      excelData: {
        header: null,
        results: null
      },

      // 打印
      printObj: {
        id: 'printMe',
        popTitle: '打印表格名字',
        extraCss:
          'https://cdn.bootcdn.net/ajax/libs/animate.css/4.1.1/animate.compat.css, https://cdn.bootcdn.net/ajax/libs/hover.css/2.3.1/css/hover-min.css',
        extraHead:
          '<meta http-equiv="Content-Language"content="zh-cn"/>,<style>.el-table__header {`width`: 100% !important;}</style>',
        beforeOpenCallback(vue) {
          console.log('打开之前')
        },
        openCallback(vue) {
          console.log('执行了打印')
        },
        closeCallback(vue) {
          console.log('关闭了打印工具')
        }
      }
    }
  },
  mounted() {
    const arr = [
      {

        name: '张三',
        address: '上海市普陀区金沙江路 1518 弄',
        date: '1998-10-08 01:57',
        timestamp1: 1455254121,
        timestamp2: 1455254121,
        timestamp3: 1455254121,
        timestamp4: 1455254121,
        timestamp5: 1455254121
      },
      {

        name: '王小虎',
        address: '上海市普陀区金沙江路 1517 弄',
        date: '1998-10-08 01:57',
        timestamp1: 1455254121,
        timestamp2: 1455254121,
        timestamp3: 1455254121,
        timestamp4: 1455254121,
        timestamp5: 1455254121
      },
      {

        name: '阿雄',
        address: '上海市普陀区金沙江路 1519 弄',
        date: '1991-10-08 01:57',
        timestamp1: 1455254121,
        timestamp2: 1455254121,
        timestamp3: 1455254121,
        timestamp4: 1455254121,
        timestamp5: 1455254121
      },
      {

        name: '阿雄',
        address: '上海市普陀区金沙江路 1519 弄',
        date: '1991-10-08 01:57',
        timestamp1: 1455254121,
        timestamp2: 1455254121,
        timestamp3: 1455254121,
        timestamp4: 1455254121,
        timestamp5: 1455254121
      },
      {

        name: '阿雄',
        address: '上海市普陀区金沙江路 1519 弄',
        date: '1991-10-08 01:57',
        timestamp1: 1455254121,
        timestamp2: 1455254121,
        timestamp3: 1455254121,
        timestamp4: 1455254121,
        timestamp5: 1455254121
      },
      {

        name: '阿雄',
        address: '上海市普陀区金沙江路 1519 弄',
        date: '1991-10-08 01:57',
        timestamp1: 1455254121,
        timestamp2: 1455254121,
        timestamp3: 1455254121,
        timestamp4: 1455254121,
        timestamp5: 1455254121
      }
    ]
    this.tableData = [...arr, ...arr, ...arr, ...arr, ...arr, ...arr]
  },
  methods: {
    // href 下载
    // 后端返回下载url

    handleDownloadHref() {
      this.$confirm('确定href下载表格', 'href 下载xslx', {
        type: 'warning'
      }).then((res) => {
        location.href =
          'http://127.0.0.1:3000/public/vue2admin/testbiaoge.xlsx'
      })
    },

    // xlsx导出
    handleDownload() {
      import('@/utils/Export2Excel').then((excel) => {
        // 由于js-xlsx体积还是很大的，导出功能也不是一个非常常用的功能，所以使用的时候建议使用懒加载
        const tHeader = ['姓名', '地址', '日期', '时间戳'] //
        const filterVal = ['name', 'address', 'date', 'timestamp1'] // 对应每项数据的属性
        const list = this.tableData
        const data = this.formatJson(filterVal, list)
        excel.export_json_to_excel({
          header: tHeader, // 导出数据的表头	Array
          data, // 导出的具体数据	Array
          filename: this.filename, // 导出文件名
          autoWidth: this.autoWidth, // 单元格是否要自适应宽度
          bookType: this.bookType // 导出文件类型		xlsx, csv, txt, more
        })
      })
    },
    /*
     此方法就是将表格数据row 数据 装成对应数组
     @prams filterVal  ==>对应表格数据的每项的属性 ['name', 'address', 'date', 'timestamp']
     @prams jsonData 表格数据
    */
    formatJson(filterVal, jsonData) {
      return jsonData.map((v) =>
        filterVal.map((j) => {
          if (j === 'timestamp') {
            return parseTime(v[j])
          } else {
            return v[j]
          }
        })
      )
    },

    // 导入
    // input 失去焦点并且它的value值发生变化时触发
    handleClick(e) {
      const files = e.target.files
      const rawFile = files[0] // only use files[0]
      if (!rawFile) return
      this.upload(rawFile)
    },
    // 上传表格 点击按钮触发
    btnClick() {
      this.$refs['excel-upload-input'].click()
    },
    // 真正上传方法
    // @parms rawFile 上传的文件流 file
    upload(rawFile) {
      this.$refs['excel-upload-input'].value = null // 修复程序无法选择相同的excel
      if (!this.beforeUpload) { // 上传前校验不通过
        this.readerData(rawFile) //
        return
      }
      const before = this.beforeUpload(rawFile)
      if (before) {
        this.readerData(rawFile)
      }
    },
    // 上传前校验文件大小需小于1M
    beforeUpload(file) {
      const isLt1M = file.size / 1024 / 1024 < 1
      if (isLt1M) {
        return true
      }
      this.$message({
        message: 'Please do not upload files larger than 1m in size.',
        type: 'warning'
      })
      return false
    },
    // 读取内容
    readerData(rawFile) {
      return new Promise((resolve, reject) => {
        const reader = new FileReader()
        reader.onload = (e) => {
          const data = e.target.result
          const workbook = XLSX.read(data, { type: 'array' })
          const firstSheetName = workbook.SheetNames[0]
          const worksheet = workbook.Sheets[firstSheetName]
          const header = this.getHeaderRow(worksheet)
          const results = XLSX.utils.sheet_to_json(worksheet)
          this.generateData({ header, results }) // 生成数据
          resolve()
        }
        reader.readAsArrayBuffer(rawFile)
      })
    },
    getHeaderRow(sheet) {
      const headers = []
      const range = XLSX.utils.decode_range(sheet['!ref'])
      let C
      const R = range.s.r
      /* start in the first row */
      for (C = range.s.c; C <= range.e.c; ++C) {
        /* walk every column in the range */
        const cell = sheet[XLSX.utils.encode_cell({ c: C, r: R })]
        /* find the cell in the first row */
        let hdr = 'UNKNOWN ' + C // <-- replace with your desired default
        if (cell && cell.t) hdr = XLSX.utils.format_cell(cell)
        headers.push(hdr)
      }
      return headers
    },
    generateData({ header, results }) {
      this.excelData.header = header
      this.excelData.results = results
      this.onSuccess && this.onSuccess(this.excelData)
    },
    onSuccess({ results, header }) {
      this.tableData2 = results
      this.tableHeader = header
      console.log('re', this.tableHeader)
      console.log('re', this.tableData2)
    }
  }
}
</script>

<style lang="scss" scoped>
@import "~@/styles/mixin.scss";
::v-deep .el-table--scrollable-x .el-table__body-wrapper {
  @include scrollBar;
}

// 原生测试表格
.my_test_table{
border: 0.5px solid #eceef1;
width: 100%;
background: #fff;
border-spacing: 0px;
color: #555;
th,td{
  text-align: center;
  border: 0.5px solid #eceef1;
  padding: 6px 4px;
}
th{
  color: #333;
}
.t_address{
  width: 200px;
}
}

// 打印媒体查询
// 打印媒体查询

#printMe {
  width: 100%;
}

@media print {
    #printMe table {
    width: 100% !important;
  }
  #printMe table thead{
    width: 100% !important;
  }
  #printMe .el-table__header-wrapper .el-table__header {
    width: 100% !important;
    border: solid 1px #f2f2f2;
  }
  #printMe .el-table__body-wrapper .el-table__body {
    width: 100% !important;
  }
  #printMe #pagetable table {
    table-layout: fixed !important;
  }
}

.richtext {
  @include main-padding;
  .excel-upload-input {
    display: none;
    z-index: -9999;
  }
}
</style>
